package com.cn.xly2023.service;

import com.cn.xly2023.mapper.GoodMapper;
import com.cn.xly2023.mapper.UserMapper;
import com.cn.xly2023.pojo.Good;
import com.cn.xly2023.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private GoodMapper goodMapper;
    public Map<String, Object> selectById(Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", userMapper.selectById(id));
        return map;
    }

    public Map<String, Object> selectAll() {
        List<User> userList = userMapper.selectAll();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", userList.size());
        map.put("data", userList);
        return map;
    }

    public Map<String, Object> selectByPage(Integer page, Integer limit,
                                            String username, Integer age) {
        int index = (page - 1) * limit;
        List<User> userList = userMapper.selectByPage(index, limit, username, age);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", userMapper.selectCount(username, age));
        map.put("data", userList);
        return map;
    }

    public Map<String, Object> insert(User user) {
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));   // 把当前服务器时间设置到创建时间中
        user.setPassword(md5(user.getUsername(), user.getPassword()));   // 基于shiro的加密加盐机制进行加密处理
        userMapper.insert(user);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "新增用户成功");
        map.put("user", user);
        return map;
    }

    public Map<String, Object> updateById(Integer id, Integer age) {
        userMapper.updateById(id, age);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "更新用户成功");
        return map;
    }

    public Map<String, Object> deleteById(Integer id) {
        userMapper.deleteById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "删除用户成功");
        return map;
    }

//    public Map<String, Object> login(String username, String password) {
//        User loginUser = userMapper.login(username);
//        Map<String, Object> map = new HashMap<>();
//        if(loginUser == null) {
//            map.put("code", 50001);
//            map.put("msg", "用户名不存在");
//        }
//        else if(loginUser.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))) {
//            map.put("code", 200);
//            map.put("msg", "登录成功");
//        }
//        else {
//            map.put("code", 50002);
//            map.put("msg", "密码错误");
//        }
//        return map;
//    }

    public Map<String, Object> login(String username, String password) {
        Map<String, Object> map = new HashMap<>();
//        System.out.println("username:"+username);
//        System.out.println("password:"+password);
        Subject subject = SecurityUtils.getSubject();                                     // shiro权限认证主体对象
        if (!subject.isAuthenticated()) {
            UsernamePasswordToken upToken = new UsernamePasswordToken(username, password);    // shiro权限认证类型
            upToken.setRememberMe(true);                                                     // 用户登录时效性
            try {
                subject.login(upToken);    // 调用realm认证用户权限
                map.put("code", 200);
                map.put("msg", "登录成功");
                return map;
            } catch (IncorrectCredentialsException ice) {
                System.out.println("用户名/密码不匹配~");
                map.put("code", 5001);
                map.put("msg", "用户名/密码不匹配！");
                return map;
            } catch (LockedAccountException lae) {
                System.out.println("账户已被冻结！");
                map.put("code", 5002);
                map.put("msg", "账户已被冻结！");
                return map;
            } catch (UnknownAccountException uae) {
                System.out.println("账户不存在");
                map.put("code", 5003);
                map.put("msg", "账户不存在");
                return map;
            } catch (AuthenticationException ae) {
                System.out.println("未知的错误");
                System.out.println(ae.getMessage());
                map.put("code", 5004);
                map.put("msg", "未知的错误");
                return map;
            }
        }
        else {
            // 如果用户在没有退出的情况，再次输入用户名和密码登录，那么可以在这里执行操作
        }
        map.put("code", 50005);                              // 这两行的作用是避免用户重复登录
        map.put("msg", "登录异常，请稍候重试");
        return map;
    }

    public User getUser(String username) {
        return userMapper.login(username);
    }

    public String test01() {
        return "hello Springboot";
    }

    // 注册时，进行shiro加密，返回加密后的结果，如果在加入shiro之前，存在用户密码不是此方式加密的，那么将无法登录
    // 使用用户名作为盐值
    private static String md5(String username, String password){
        String hashAlgorithmName = "MD5";                   // 加密方式
        ByteSource salt = ByteSource.Util.bytes(username);  // 以账号作为盐值
        int hashIterations = 11;                            // 加密11次
        return new SimpleHash(hashAlgorithmName, password, salt, hashIterations).toString();
    }

    public static void main(String[] args) {
        System.out.println(md5("gxa04","123456"));

    }
}
